package top.melody.ecommerce.webapps.www.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.melody.ecommerce.common.util.JsonMapper;
import top.melody.ecommerce.common.util.RandomRange;
import top.melody.ecommerce.platform.handler.enums.ResultMsg;
import top.melody.ecommerce.platform.props.GlobalConfig;
import top.melody.ecommerce.webapps.www.base.AssertContext;
import top.melody.ecommerce.webapps.www.base.Constant;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author: blentle
 * @group: rd
 * @createdate: 2016/11/15 17:59
 * @mail: blentle.huan.ren@gmail.com
 * @description:
 * @since:1.0
 */
@Controller
@RequestMapping("/validate/code")
public class ValidateCodeController {

    private static final Logger logger = LoggerFactory.getLogger(ValidateCodeController.class);
    @Resource
    private ResourceBundleMessageSource i18nSource;
    @Resource
    private GlobalConfig globalConfig;

    @RequestMapping("/sms/sign/up")
    @ResponseBody
    public String getSignUpSms(HttpServletRequest request) {
        ResultMsg resultMsg = new ResultMsg(ResultMsg.CODE_E, i18nSource.getMessage(Constant.ERROR_OPERATE_FAILED, null, Locale.CHINA));
        try {
            //60s后才能继续发送，随机生成6位数验证码
            String smsCode = generateSmsCode();
            AssertContext.putSmsCode2Session(smsCode, request);
            resultMsg.setStatusCode(ResultMsg.CODE_S);
            resultMsg.setResult(globalConfig.getSmsCodeRefresh());
            resultMsg.setMsg(smsCode);
        } catch (Exception e) {
            logger.error("occurred exception when get sign up sms ...", e);
        }
        return JsonMapper.nonEmptyMapper().toJson(resultMsg);
    }

    private String generateSmsCode() {
        return String.valueOf(new RandomRange(globalConfig.getSmsCodeBottom(), globalConfig.getSmsCodeTop()).nextInt());
    }
}
